const fs = require('fs');
const xlsx = require('xlsx');
const axios = require('axios');
const cron = require('node-cron');

// 加载环境变量
require('dotenv').config();

// 企业微信Webhook地址
const WECHAT_WEBHOOK = process.env.WECHAT_WEBHOOK;

// API请求延迟配置（毫秒）
const REQUEST_DELAY = parseInt(process.env.REQUEST_DELAY) || 5000;

// 检查必要的环境变量
if (!WECHAT_WEBHOOK) {
    console.error('❌ 错误：未找到企业微信Webhook地址');
    console.error('请先复制 .env.example 文件为 .env 并配置 WECHAT_WEBHOOK');
    process.exit(1);
}

// 历史数据文件路径
const DAILY_HISTORY_FILE = process.env.NODE_ENV === 'production' ? '/app/data/daily_history.json' : './daily_history.json';

// 读取Excel文件
async function readExcelFile(filePath) {
    try {
        const workbook = xlsx.readFile(filePath);
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const data = xlsx.utils.sheet_to_json(worksheet);
        return data;
    } catch (error) {
        console.error('读取Excel文件失败:', error.message);
        return [];
    }
}

// 发送API请求获取任务详情
async function getTaskDetail(id) {
    try {
        const url = `https://api-pre.prover.xyz/api/v1/zkTask/dashboard/prover/detail/${id}`;
        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error(`获取ID ${id} 的任务详情失败:`, error.message);
        return null;
    }
}

// 发送企业微信消息
async function sendWeChatMessage(message) {
    try {
        const data = {
            msgtype: 'text',
            text: {
                content: message
            }
        };
        
        const response = await axios.post(WECHAT_WEBHOOK, data, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.data.errcode === 0) {
            console.log('✅ 企业微信消息发送成功');
            return true;
        } else {
            console.error('❌ 企业微信消息发送失败:', response.data);
            return false;
        }
    } catch (error) {
        console.error('❌ 发送企业微信消息出错:', error.message);
        return false;
    }
}

// 读取历史数据
function readDailyHistory() {
    try {
        if (fs.existsSync(DAILY_HISTORY_FILE)) {
            const data = fs.readFileSync(DAILY_HISTORY_FILE, 'utf8');
            return JSON.parse(data);
        }
    } catch (error) {
        console.error('读取历史数据文件失败:', error.message);
    }
    return {};
}

// 保存历史数据
function saveDailyHistory(history) {
    try {
        fs.writeFileSync(DAILY_HISTORY_FILE, JSON.stringify(history, null, 2));
    } catch (error) {
        console.error('保存历史数据文件失败:', error.message);
    }
}

// 获取日期字符串
function getDateString(date = new Date()) {
    return date.toISOString().split('T')[0]; // YYYY-MM-DD格式
}

// 获取前一天日期字符串
function getYesterdayString() {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    return getDateString(yesterday);
}

// 获取格式化的日期显示
function getFormattedDate(dateString) {
    const date = new Date(dateString + 'T00:00:00Z');
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}年${month}月${day}日`;
}

// 生成日报数据
async function generateDailyReport() {
    console.log(`🚀 开始生成日报... ${new Date().toLocaleString()}`);

    // 读取Excel文件
    const excelData = await readExcelFile('./device.xlsx');
    
    if (excelData.length === 0) {
        console.error('Excel文件为空或读取失败');
        return null;
    }

    // 找到包含ID的列
    const idField = Object.keys(excelData[0]).find(key => 
        key.toLowerCase().includes('id') || 
        key.includes('设备') ||
        typeof excelData[0][key] === 'number'
    );

    // 找到device字段
    const deviceField = Object.keys(excelData[0]).find(key => 
        key.toLowerCase().includes('device') || 
        key.includes('设备名') ||
        key.includes('名称')
    );

    if (!idField) {
        console.error('未找到ID字段，请检查Excel文件结构');
        return null;
    }

    // 读取历史数据
    const history = readDailyHistory();
    const today = getDateString();
    const yesterday = getYesterdayString();

    // 当前数据
    const todayData = {
        date: today,
        devices: {},
        summary: {
            totalDevices: 0,
            successCount: 0,
            totalRewardCYS: 0,
            totalTasks: 0,
            totalFinishedTasks: 0
        }
    };

    // 收集所有设备的当前数据
    for (const row of excelData) {
        const deviceId = row[idField];
        const deviceName = deviceField ? row[deviceField] : `设备${deviceId}`;
        if (!deviceId) continue;

        todayData.summary.totalDevices++;
        
        const taskDetail = await getTaskDetail(deviceId);
        
        if (taskDetail && taskDetail.code === 0) {
            const data = taskDetail.data;
            todayData.summary.successCount++;
            todayData.summary.totalRewardCYS += parseFloat(data.rewardCYS || 0);
            todayData.summary.totalTasks += parseInt(data.totalTask || 0);
            todayData.summary.totalFinishedTasks += parseInt(data.finishTask || 0);
            
            todayData.devices[deviceId] = {
                name: deviceName,
                rewardCYS: parseFloat(data.rewardCYS || 0),
                totalTask: parseInt(data.totalTask || 0),
                finishTask: parseInt(data.finishTask || 0),
                status: data.status
            };
        } else {
            todayData.devices[deviceId] = {
                name: deviceName,
                rewardCYS: 0,
                totalTask: 0,
                finishTask: 0,
                status: 0,
                error: true
            };
        }
        
        // 添加延迟避免请求过于频繁
        await new Promise(resolve => setTimeout(resolve, REQUEST_DELAY)); // 可配置延迟，避免403错误
    }

    // 保存今日数据到历史记录
    history[today] = todayData;
    saveDailyHistory(history);

    // 生成报告
    const report = {
        today: todayData,
        yesterday: history[yesterday] || null,
        comparison: null,
        deviceChanges: [],
        alertDevices: []
    };

    // 如果有昨天的数据，进行对比
    if (report.yesterday) {
        report.comparison = {
            rewardCYSChange: todayData.summary.totalRewardCYS - report.yesterday.summary.totalRewardCYS,
            totalTasksChange: todayData.summary.totalTasks - report.yesterday.summary.totalTasks,
            finishedTasksChange: todayData.summary.totalFinishedTasks - report.yesterday.summary.totalFinishedTasks
        };

        // 分析每个设备的变化
        Object.keys(todayData.devices).forEach(deviceId => {
            const todayDevice = todayData.devices[deviceId];
            const yesterdayDevice = report.yesterday.devices[deviceId];

            if (yesterdayDevice) {
                const change = {
                    deviceId: deviceId,
                    name: todayDevice.name,
                    rewardChange: todayDevice.rewardCYS - yesterdayDevice.rewardCYS,
                    taskChange: todayDevice.totalTask - yesterdayDevice.totalTask,
                    finishChange: todayDevice.finishTask - yesterdayDevice.finishTask,
                    todayReward: todayDevice.rewardCYS,
                    todayTasks: todayDevice.totalTask,
                    todayFinished: todayDevice.finishTask
                };

                // 计算失败任务数（如果总任务数减少）
                if (change.taskChange < 0) {
                    change.failedTasks = Math.abs(change.taskChange);
                } else {
                    change.failedTasks = 0;
                }

                // 计算实际完成的任务数（排除失败的影响）
                change.actualCompleted = change.finishChange;

                report.deviceChanges.push(change);

                // 检查是否需要警报（连续两天无变化）
                if (change.rewardChange === 0 && change.taskChange === 0 && change.finishChange === 0) {
                    // 检查前天的数据
                    const dayBeforeYesterday = getDateString(new Date(new Date(yesterday).getTime() - 24 * 60 * 60 * 1000));
                    const dayBeforeData = history[dayBeforeYesterday];
                    
                    if (dayBeforeData && dayBeforeData.devices[deviceId]) {
                        const dayBeforeDevice = dayBeforeData.devices[deviceId];
                        const prevChange = {
                            rewardChange: yesterdayDevice.rewardCYS - dayBeforeDevice.rewardCYS,
                            taskChange: yesterdayDevice.totalTask - dayBeforeDevice.totalTask,
                            finishChange: yesterdayDevice.finishTask - dayBeforeDevice.finishTask
                        };

                        // 如果前天也没有变化，添加到警报列表
                        if (prevChange.rewardChange === 0 && prevChange.taskChange === 0 && prevChange.finishChange === 0) {
                            report.alertDevices.push({
                                deviceId: deviceId,
                                name: todayDevice.name,
                                daysWithoutChange: 2
                            });
                        }
                    }
                }
            }
        });
    }

    return report;
}

// 生成企业微信消息
function generateWeChatMessage(report) {
    const today = getFormattedDate(report.today.date);
    let message = `📊 Cysic每日任务报告\n\n`;
    message += `📅 日期: ${today}\n\n`;

    // 当前总体情况
    message += `📈 总体情况:\n`;
    message += `总分: ${report.today.summary.totalRewardCYS.toFixed(2)} CYS\n`;
    message += `总任务数: ${report.today.summary.totalTasks}\n`;
    message += `已完成: ${report.today.summary.totalFinishedTasks}\n`;
    message += `设备数: ${report.today.summary.successCount}/${report.today.summary.totalDevices}\n`;

    // 与昨天对比
    if (report.comparison) {
        message += `\n📊 与昨日对比:\n`;
        message += `积分变化: ${report.comparison.rewardCYSChange >= 0 ? '+' : ''}${report.comparison.rewardCYSChange.toFixed(2)} CYS\n`;
        message += `总任务变化: ${report.comparison.totalTasksChange >= 0 ? '+' : ''}${report.comparison.totalTasksChange}\n`;
        message += `完成任务变化: ${report.comparison.finishedTasksChange >= 0 ? '+' : ''}${report.comparison.finishedTasksChange}\n`;

        // 设备变化详情（只显示有变化的设备，最多10个）
        const activeDevices = report.deviceChanges.filter(device => 
            device.rewardChange !== 0 || device.taskChange !== 0 || device.finishChange !== 0
        );

        if (activeDevices.length > 0) {
            message += `\n📋 活跃设备详情:\n`;
            activeDevices.slice(0, 10).forEach((device, index) => {
                message += `${index + 1}. ${device.name}\n`;
                if (device.rewardChange !== 0) {
                    message += `   积分: ${device.rewardChange >= 0 ? '+' : ''}${device.rewardChange.toFixed(2)} CYS\n`;
                }
                if (device.actualCompleted > 0) {
                    message += `   完成任务: +${device.actualCompleted}个\n`;
                }
                if (device.failedTasks > 0) {
                    message += `   失败任务: ${device.failedTasks}个\n`;
                }
            });

            if (activeDevices.length > 10) {
                message += `... 还有${activeDevices.length - 10}个设备有变化\n`;
            }
        }
    }

    // 警报设备
    if (report.alertDevices.length > 0) {
        message += `\n⚠️  警报设备 (连续2天无变化):\n`;
        report.alertDevices.forEach((device, index) => {
            message += `${index + 1}. ${device.name} (ID: ${device.deviceId})\n`;
        });
    }

    message += `\n⏰ 报告生成时间: ${new Date().toLocaleString()}`;

    return message;
}

// 执行日报任务
async function runDailyReport() {
    try {
        console.log('🎯 开始执行每日报告任务...');
        console.log(`⏱️ API请求延迟设置: ${REQUEST_DELAY}ms`);
        
        const report = await generateDailyReport();
        
        if (!report) {
            console.error('❌ 生成日报失败');
            return;
        }

        console.log('✅ 日报数据生成完成');

        // 生成企业微信消息
        const message = generateWeChatMessage(report);
        
        console.log('\n📝 生成的报告消息:');
        console.log('='.repeat(50));
        console.log(message);
        console.log('='.repeat(50));

        // 发送企业微信通知
        const sent = await sendWeChatMessage(message);
        
        if (sent) {
            console.log('✅ 日报发送成功');
        } else {
            console.log('❌ 日报发送失败');
        }

    } catch (error) {
        console.error('❌ 执行日报任务出错:', error);
        
        // 发送错误通知
        const errorMessage = `❌ Cysic日报生成失败\n\n错误信息: ${error.message}\n时间: ${new Date().toLocaleString()}`;
        await sendWeChatMessage(errorMessage);
    }
}

// 启动定时任务
function startDailyReportSchedule() {
    console.log('🎯 启动Cysic每日报告系统...\n');
    
    // 每天8点(北京时间UTC+8)执行日报任务
    cron.schedule('0 8 * * *', async () => {
        console.log('\n' + '='.repeat(60));
        console.log('⏰ 定时任务触发 - 开始生成每日报告');
        await runDailyReport();
    }, {
        timezone: "Asia/Shanghai"
    });
    
    console.log('⏰ 每日报告定时任务已启动');
    console.log('📅 执行时间: 每天北京时间8:00');
    console.log('📊 报告内容: 设备任务完成情况、积分变化、异常设备警报');
    console.log('📱 通知方式: 企业微信');
    console.log('\n💡 手动执行测试: npm run daily-report');
    console.log('按 Ctrl+C 停止定时任务\n');
}

// 命令行参数处理
const args = process.argv.slice(2);

if (args.includes('--run-now') || args.includes('-r')) {
    // 立即执行一次日报
    console.log('🚀 手动执行日报任务...\n');
    runDailyReport().then(() => {
        console.log('\n✅ 手动执行完成');
        process.exit(0);
    }).catch(error => {
        console.error('\n❌ 手动执行失败:', error);
        process.exit(1);
    });
} else if (args.includes('--help') || args.includes('-h')) {
    // 显示帮助信息
    console.log(`
📊 Cysic每日报告系统

用法:
  node dailyReport.js              启动定时任务 (每天UTC 8:00执行)
  node dailyReport.js --run-now    立即执行一次日报
  node dailyReport.js --help       显示此帮助信息

功能:
  - 每日8点(北京时间)自动生成任务完成报告
  - 统计所有设备的积分和任务变化
  - 对比前一天数据，分析完成和失败情况
  - 检测连续2天无变化的异常设备
  - 自动发送报告到企业微信

文件:
  - daily_history.json: 历史数据存储文件
  - device.xlsx: 设备列表文件
`);
} else {
    // 默认启动定时任务
    startDailyReportSchedule();
}

// 优雅退出处理
process.on('SIGINT', () => {
    console.log('\n👋 收到退出信号，正在关闭定时任务...');
    process.exit(0);
});

process.on('SIGTERM', () => {
    console.log('\n👋 收到终止信号，正在关闭定时任务...');
    process.exit(0);
}); 